package com.liujun.spring4.demo.aop.iocset.dynBean.beanfactory;

import com.liujun.spring4.demo.aop.iocset.dynBean.beanfactory.service.LogonService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;

/**
 * 通过DefaultListableBeanFactory动态的添加Bean
 * @author liujun
 * @version 1.0
 * @date 2018-08-23 08:07:00
 */
public class UserServiceFactoryBean implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory bf) throws BeansException {
        //1,将ConfigurableListableBeanFactory转化为DefaultListableBeanFactory
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)bf;

        //2,通过BeanDefinitionBuilder创建Bean
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(LogonService.class);

        //设置属性UserDao,此属性引用已经定义的Bean:userDao
        beanDefinitionBuilder.addPropertyReference("userDao","userDao");

        //注册Bean定义
        beanFactory.registerBeanDefinition("userService1",beanDefinitionBuilder.getRawBeanDefinition());

        //直接注册一个Bean实例
        beanFactory.registerSingleton("userService2",new LogonService());

    }
}
